using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace SharpObjects.Utils
{
    public class MutexLock : ISyncLock
    {
        public string Name;
        public Mutex mutex;

        protected bool m_bAcquired = false;

        public MutexLock(string sName)
        {
            Name = sName;
            mutex = new Mutex(false, sName);
        }

        public MutexLock(string sName, bool bAcquireLock)
        {
            Name = sName;
            mutex = new Mutex(false, sName);

            if (bAcquireLock)
            {
                Acquire();
            }
        }

        public MutexLock(string sName, bool bAcquireLock, TimeSpan timeout)
        {
            Name = sName;
            mutex = new Mutex(false, sName);

            if (bAcquireLock)
            {
                Acquire(timeout);
            }
        }

        //#region ISyncLock Members

        public void Acquire()
        {
            if (!m_bAcquired)
            {
                mutex.WaitOne();
                m_bAcquired = true;
            }
        }

        public void Acquire(int nTimeoutMsec)
        {
            Acquire(TimeSpan.FromMilliseconds(nTimeoutMsec));
        }

        public void Acquire(TimeSpan timeout)
        {
            if (!m_bAcquired)
            {
                mutex.WaitOne(timeout, true);
                m_bAcquired = true;
            }
        }

        public void Release()
        {
            if (m_bAcquired)
            {
                mutex.ReleaseMutex();
                m_bAcquired = false;
            }
        }

        //#endregion

        //#region IDisposable Members

        public void Dispose()
        {
            Release();
        }

        //#endregion
    }
}
